package database

import (
	"fmt"
	"github.com/cn-zhangjie/postgresql-to-struct/pkg/settings"
	"github.com/jmoiron/sqlx"
	_ "github.com/lib/pq"
	"os"
	"strconv"
	"strings"
)

var Instance *sqlx.DB

func init() {
	fmt.Println("正在连接数据库...")

	var build strings.Builder
	build.WriteString("host=")
	build.WriteString(settings.DatabaseSetting.Host)

	// 注意空格分隔
	build.WriteString(" port=")
	build.WriteString(strconv.Itoa(settings.DatabaseSetting.Port))

	build.WriteString(" user=")
	build.WriteString(settings.DatabaseSetting.Username)

	build.WriteString(" password=")
	build.WriteString(settings.DatabaseSetting.Password)

	build.WriteString(" dbname=")
	build.WriteString(settings.DatabaseSetting.InitDatabaseName)

	build.WriteString(" sslmode=")
	build.WriteString(settings.DatabaseSetting.SSLMode)

	db, err := sqlx.Connect("postgres", build.String())
	if err != nil {
		// 非常严重的错误，到这里会中断程序
		fmt.Println("啊~数据库配置错误：", err)
		os.Exit(0)
	}
	Instance = db
	fmt.Println("数据库连接成功")
}

// 关闭数据库连接
func Close() {
	if Instance != nil {
		if err := Instance.Close(); err != nil {
			fmt.Println("数据库关闭失败：", err)
		} else {
			fmt.Println("数据库关闭成功")
		}
	}
}
